# -*- coding: utf8 -*-

from project.sqlite3_db.table import Table

class TableDirectory( Table ):

    _table_name = "directory"

    def create( self ):
        cur = self.getCursor()

        # Create table
        cur.execute(
            "CREATE TABLE IF NOT EXISTS directory ("+
            "id INTEGER PRIMARY KEY, "+
            "parent_id INTEGER, "+
            "device INTEGER, "+
            "name TEXT)"
        )

        cur.close()
        return


    def save_directory( self, parent_id, device, name ):
        cur = self.getCursor()

        cur.execute("INSERT INTO directory(parent_id, device, name) VALUES (?, ?, ?)", (parent_id, device, name))
        self.getConnection().commit()
        dir_id = cur.lastrowid

        cur.close()
        return dir_id


    def get_file_full_path( self, item ):

        cur = self.getCursor()

        paths = [ item["name"] ]

        parent = item["parent_id"]

        while parent:

            cur.execute("SELECT * FROM directory WHERE id=:id",
                    {"id": parent}
            )
            dir_item = cur.fetchone()

            paths.append( dir_item["name"] )
            parent = dir_item["parent_id"]

        paths.reverse()

        import os
        full_path = os.sep.join(paths)

        cur.close()
        return full_path

    pass
